from static.configfile.config import *
from xpinyin import Pinyin
from pymongo import MongoClient
import time
import re
from datetime import datetime,timedelta
ping_list = { "weixin": "微信", "weiboAPI": "微博API","weiboScrapy": "微博Scrapy", "wangmei": "网媒" ,"baidu": "百度"}
pingtai = { "微信": "weixin", "微博API": "weiboAPI", "微博Scrapy": "weiboScrapy","网媒": "wangmei","百度": "baidu" }
   

p = Pinyin()
url = mongo_url_to_db

# 发展趋势数据处理
def development(name):
    dbname = "doc_"+str(p.get_pinyin(name,""))
    client =MongoClient(mongo_url_to_db)
    collection = client["Task"][dbname]
    # 转换成标准格式的年月日
    def to_ymd(x) -> str:
        return time.strftime("%Y-%m-%d",time.localtime(x*86400+28800))
    yarr = {}
    for i in collection.aggregate([{"$project":{"_id":0,"id":1,"channel":1,"getTime":1,"ymd":{"$divide":[{"$subtract":[{"$add":["$getTime",28800]},{"$mod":[{"$add":["$getTime",28800]},86400]}]},86400]}}},{'$group': {'_id': {"channel":'$channel',"ymd":"$ymd"},'count': {'$sum': 1}}},{"$project":{"_id":0,"channel":"$_id.channel","ymd":"$_id.ymd","count":1}}]):
        yarr.setdefault(i["channel"],{})
        yarr[i["channel"]][to_ymd(i["ymd"])] = i["count"]
    # 横坐标，时间轴
    collection = client["Task"]["task"]
    xDataArr = []
    tt = datetime(1970,1,1)
    fromdays = float("inf")
    fd = datetime(time.localtime().tm_year, time.localtime().tm_mon, time.localtime().tm_mday)
    for i in collection.find({"name":name}):
        f = [int(y) for y in re.findall(r"\"fromdate\": \"(\d{4}-\d{2}-\d{2})",i["canshu"])[0].split("-")]
        fromdays = datetime(f[0], f[1], f[2])
        fd =fromdays if (fromdays-tt).days < (fd-tt).days else fd
    fromdate = fd
    print(fromdate.strftime("%Y-%m-%d"))
    f = [int(y) for y in fromdate.strftime("%Y-%m-%d") .split("-")]
    fd = datetime(f[0], f[1], f[2])
    savedate = ""
    Days = 0
    for i in collection.find({"name":name}):
        t = [int(y) for y in i["savetime"].split("-")]
        td = datetime(t[0], t[1], t[2])
        Days =(td-fd).days if (td-fd).days > Days else Days
    print(Days)
    # # savedate = 
    
    # f = [int(y) for y in fromdate.split("-")]
    # t = [int(y) for y in savedate.split("-")]
    # td = datetime(t[0], t[1], t[2])
    # fd = datetime(f[0], f[1], f[2])
    # Days = (td-fd).days
    xDataArr.append(fd.strftime("%Y-%m-%d"))
    for i in range(Days):
        fd=fd+timedelta(days=+1)
        xDataArr.append(fd.strftime("%Y-%m-%d"))

    # 纵坐标 每个平台数据量
    legend = list(yarr.keys())
    series =[]
    for l in legend:
        temp = yarr[l]
        data = []
        for d in xDataArr:
            data.append(temp.setdefault(d,0))
        y = {
                "type": 'line',
                "areaStyle":{},
                "stack": 'Total'
            }
        y["name"] = ping_list[l]
        y["data"] = data
        series.append(y)
    chartdata = {}
    chartdata["xDataArr"] = xDataArr
    chartdata["series"] = series
    chartdata["legend"] = [ping_list[i] for i in legend]
    return chartdata

# 词云图请求返回的完整数据
def wordcloud(name):
    # dbname = "doc_"+str(p.get_pinyin(request.args.get("dbname"),""))    
    dbname = "doc_"+str(p.get_pinyin(name,""))
    client =MongoClient(mongo_url_to_db)
    collection = client["Task"][dbname]

if __name__ == "__main__":
    # 发展趋势折线图数据请求返回的完整数据
    chartdata = development("肖战")

    # 词云图数据请求返回的完整数据
    word = wordcloud("肖战")